package com.qijian.web.controller.system;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import com.qijian.common.core.domain.entity.SysUser;
import com.qijian.common.utils.uuid.IdUtils;
import com.qijian.system.domain.UserGroup;
import com.qijian.system.domain.vo.UserGroupQuery;
import com.qijian.system.service.ISysUserService;
import com.qijian.system.service.IUserGroupService;
import lombok.RequiredArgsConstructor;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qijian.common.annotation.Log;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;
/**
 * 人员分组Controller
 *
 * @author qijian
 * @date 2022-10-11
 */
@Api(tags = "人员分组")
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/group")
public class UserGroupController extends BaseController {

    private final IUserGroupService userGroupService;
    private final ISysUserService userService;

    /**
     * 查询人员分组列表
     */
//    @PreAuthorize("@ss.hasPermi('system:userGroup:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserGroupQuery query, Page<UserGroup> page) {
        query.setParentId(0L);
        initOrderItem(UserGroup.class, page.orders());
        return getDataTable(userGroupService.page(page, WhereEntityTool.invoke(query)));
    }

    /**
     * 导出人员分组列表
     */
//    @PreAuthorize("@ss.hasPermi('system:userGroup:export')")
    @Log(title = "人员分组" , businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(UserGroupQuery query, HttpServletResponse response) {
        new ExcelUtil<>(UserGroup. class).exportExcel(response,userGroupService.list( WhereEntityTool.invoke(query)), "人员分组数据");
    }

    /**
     * 获取人员分组详细信息
     */
//    @PreAuthorize("@ss.hasAnyPermi('system:userGroup:list,system:userGroup:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        UserGroup userGroup = userGroupService.getById(id);
        if (userGroup != null) {
            UserGroupQuery query = new UserGroupQuery();
            query.setParentId(id);
            userGroup.setUsers(userGroupService.list(WhereEntityTool.invoke(query)));
        }
        return AjaxResult.success(userGroup);
    }

    /**
     * 新增人员分组
     */
//    @PreAuthorize("@ss.hasPermi('system:userGroup:add')")
    @Log(title = "人员分组" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserGroup userGroup) {
        userGroup.setId(IdUtils.singletonSnowId());
        Boolean b = userGroupService.save(userGroup);

        if (CollUtil.isNotEmpty(userGroup.getUsers())) {
            userGroup.getUsers().forEach(x -> {
                x.setParentId(userGroup.getId());
                x.setCode(userGroup.getCode());
                x.setName(userGroup.getName());
            });
            userGroupService.saveBatch(userGroup.getUsers());
        }
        return toAjax(b);

    }

    /**
     * 修改人员分组
     */
//    @PreAuthorize("@ss.hasPermi('system:userGroup:edit')")
    @Log(title = "人员分组" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserGroup userGroup) {
        approval(userGroupService.getById(userGroup.getId()));
        boolean b = userGroupService.updateById(userGroup);

        UserGroupQuery query = new UserGroupQuery();
        query.setParentId(userGroup.getId());
        userGroupService.remove(WhereEntityTool.invoke(query));

        if (CollUtil.isNotEmpty(userGroup.getUsers())) {
            userGroup.getUsers().forEach(x -> x.setParentId(userGroup.getId()));
            userGroupService.saveBatch(userGroup.getUsers());
        }
        return toAjax(b);
    }

    /**
     * 删除人员分组
     */
//    @PreAuthorize("@ss.hasPermi('system:userGroup:remove')")
    @Log(title = "人员分组" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        ids.forEach(id -> approval(userGroupService.getById(id)));
        return toAjax(userGroupService.removeByIds(ids));
    }


}
